package site.teamo.biu.flink.web.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import site.teamo.biu.flink.web.entity.UserDO;
import site.teamo.biu.flink.web.exception.BiuResponseCode;
import site.teamo.biu.flink.web.mapper.UserMapper;
import site.teamo.biu.flink.web.service.UserService;

/**
 * @author haocongshun
 * @date 2023/10/30 10:06:14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {
    @Override
    public boolean verify(String username, String password) {
        UserDO user = this.getOne(new LambdaQueryWrapper<UserDO>()
                .eq(UserDO::getUsername, username)
                .eq(UserDO::getPassword, DigestUtil.md5Hex(password))
                .select(UserDO::getUsername));
        return user != null;
    }

    @Override
    public boolean changePassword(String username, String oldPassword, String newPassword) {
        if (!getBaseMapper().exists(new LambdaQueryWrapper<UserDO>()
                .eq(UserDO::getUsername, username)
                .eq(UserDO::getPassword, DigestUtil.md5Hex(oldPassword)))) {
            throw BiuResponseCode.GENERAL_ERROR.runtimeException("密码错误");
        }
        return getBaseMapper().update(new LambdaUpdateWrapper<UserDO>()
                .eq(UserDO::getUsername, username)
                .set(UserDO::getPassword, DigestUtil.md5Hex(newPassword))) > 0;
    }
}
